package net.ustc.javamemcached.diskstore;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.ustc.javamemcached.Key;
import net.ustc.javamemcached.memorystore.MemoryEntry;

public class FileStoreManagerImpl implements IDiskStoreManager {
	final Logger log = LoggerFactory.getLogger(FileStoreManagerImpl.class);

	private MessageDigest md;
	private String dir;
	private ReentrantReadWriteLock lock;

	public FileStoreManagerImpl() {

	}

	/**
	 * 
	 * @param dir
	 *            is the root dir of disk store.
	 */
	public FileStoreManagerImpl(String dir) {
		this.dir = dir;
		lock = new ReentrantReadWriteLock();
		try {
			md = MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			System.out.println("can not init message digest");
			e.printStackTrace();
		}
	}

	public void close() {
		// TODO Auto-generated method stub

	}

	public boolean delete(Key key) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean deleteAll() {
		// TODO Auto-generated method stub
		return false;
	}

	public MemoryEntry get(Key key) {
		// TODO Auto-generated method stub
		return null;
	}

	public void open() {
		// TODO Auto-generated method stub

	}

	public boolean put(Key key, MemoryEntry entry) {
		// TODO Auto-generated method stub
		return false;
	}

	/**
	 * the file is in the disk store root dir.
	 * 
	 * @param key
	 * @return
	 */
	private String getFileName(Key key) {
		byte[] bytes;
		try {
			lock.writeLock().lock();
			md.reset();
			md.update(key.bytes.array());
			bytes = md.digest();
		} finally {
			lock.writeLock().unlock();
		}
		StringBuilder sb = new StringBuilder();
		sb.append(Integer.toHexString((int) (bytes[0] & 255)));
		sb.append('/');
		sb.append(Integer.toHexString((int) (bytes[1] & 255)));
		sb.append('/');
		for (int i = 0; i < bytes.length; i++) {
			sb.append(Integer.toHexString((int) (bytes[i] & 255)));
		}
		return sb.toString();
	}

}
